import { loginAPI } from '@/apis/user'
import { TOKEN_KEY } from '@/constants/KEY'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getProfileAPI } from '@/apis/user'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    profile: {}
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    clearUserInfo(state) {
      // 清除Token
      state.token = ''
      state.profile = {}
      removeToken(TOKEN_KEY)
    },
    setProfile(state, profile) {
      state.profile = profile
    }
  },
  actions: {
    async Login(context, { username, password }) {
      // 1.调用接口
      const res = await loginAPI({ username, password })
      // console.log('res的数据', res)
      // 2.提交mutation
      context.commit('setToken', res.data.token)
    },
    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      return res.data.permissions
    }
  }
}
